<template>
  <div class="line-chart">
    <h4>{{ title }}</h4>
    <div class="chart">
      <chart
        ref="chartRef"
        :option="refChartOption"
        :style="{ height: chartHeight }"
        @zrender:click="renderClickHandle"
        @selected:click="handleselected"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, onMounted } from 'vue';
import { Chart } from '@/components';
import echarts from 'echarts';
import moment from 'moment';
export interface TimelineItem {
  [key: string]: string | number;
}
import line1 from '@/assets/image/statistics/line1.svg';
import line2 from '@/assets/image/statistics/line2.svg';
import line3 from '@/assets/image/statistics/line3.svg';
import line4 from '@/assets/image/statistics/line4.svg';
export default defineComponent({
  props: {
    data: {
      type: Object,
      default: () => {},
    },
    title: {
      type: String,
      default: '',
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        values: ['value'],
      }),
    },
    yjLevel: {
      type: String,
      default: '',
    },
    period: {
      type: String,
      default: '',
    },
    height: {
      type: Number,
      default: 300,
    },
    type: {
      type: String,
      default: '0',
    },
    time: {
      type: String,
      default: '',
    },
    ratio: {
      type: String,
      default: '',
    },
    legend: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  setup(props, { emit }) {
    const chartRef = ref<any>();
    const line = ref<string>('');
    const color = ref<string>('#E99220');
    const areaStyle = ref<any>({});
    const chartOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'line', // 默认为直线，可选为：'line' | 'shadow'
        },
        formatter: function (Params) {
          if (props.ratio == 'T') {
            return `${Params[0].name}</br>当期警情趋势:${Params[0].value}</br>${Params[1].seriesName}:${Params[1].value}`;
          } else {
            return `${Params[0].name}</br>${Params[0].seriesName}:${Params[0].value}`;
          }
          //   return '222';
        },
      },
      legend: {
        itemWidth: 15,
        itemHeight: 2,
        data: [
          { icon: 'line', name: '当期警情趋势' },
          {
            icon: ``,
            name: '前期警情趋势',
            // itemHeight: 2, //图例的高度
            // itemWidth: 10,
          },
          //   { icon: 'line', name: '去年年度平均值' },
          //   { icon: 'none', name: '差值' },
          //   { icon: 'none', name: '同比增长' },
        ],
        formatter: function (params) {
          if (params == '差值') {
            return `${params}:${
              Difference.value == 0
                ? Difference.value + '-'
                : Difference.value > 0
                ? Difference.value + '↑'
                : Difference.value + '↓'
            } `;
          } else if (params == '同比增长') {
            return `${params}:${props.data.percent}${props.data.percent ? '%' : ''}`;
          } else {
            return params;
          }
        },
      },
      grid: {
        left: '3%',
        right: '5%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisLabel: {
          rotate: 45,
          color: function (param) {
            let colorindex =
              props.yjLevel == '1'
                ? '#FF283A'
                : props.yjLevel == '2'
                ? '#FF721C'
                : props.yjLevel == '3'
                ? '#ECD50D'
                : '#1EDEFF';
            let timer = props.time;
            if (props.period == '月') {
              let text = props.time.split('-');
              timer = text[0] + '-' + text[1];
            }
            return `${param == timer ? colorindex : '#B5B6B8'}`;
          },
          formatter: function (value) {
            if (props.period == '周') {
              return `${value}(周)`;
            }
            return value;
          },
        },
      },
      yAxis: {
        type: 'value',
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: '当期警情趋势',
          type: 'line',
          stack: '总量',
          data: [120, 132, 101, 134, 90, 230, 210],
          symbolSize: 6,
          //   symbol: 'none',
          lineStyle: {
            color: color.value,
          },

          //拐点
          itemStyle: {
            normal: {
              color: color.value,
            },
          },
          areaStyle: areaStyle.value,
        },
        {
          name: '前期警情趋势',
          type: 'line',
          data: [],
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: color.value,
              borderColor: color.value,
              lineStyle: {
                color: color.value,
                type: 'dotted',
              },
            },
          },
          markPoint: {} as any,
          emphasis: {
            itemStyle: {
              color: '',
              //   width: 4,
              //如果borderColor颜色不与color一致,则拐点处会有边框
            },
          },
          markArea: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(58,77,233,0.8)' },
                // { offset: 0.5, color: 'rgba(58, 167, 255,0.4)' },
                { offset: 1, color: 'rgba(58,77,233,0.3)' },
              ]),
            },
            data: [
              [
                {
                  //   name: '早高峰',
                  xAxis: '周一',
                },
                {
                  xAxis: '周二',
                },
              ],
            ],
          },
        },
        {
          name: '去年年度平均值',
          symbolSize: 30,
          stack: '总量',
          color: '#01844E',
          type: 'line',
          markLine: {
            symbol: ['none', 'none'], //去掉箭头
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 4,
                  height: 2,
                  color: '#01844E',
                  type: 'dotted',
                },
              },
            },
            data: [
              {
                yAxis: -1, //这里设置false是隐藏不了的，可以设置为-1
              },
            ],
          },
        },
        {
          name: '差值',
          type: 'line',
          stack: '总量',
          symbolSize: 6,
          lineStyle: {
            color: '#E99220',
          },
        },
        {
          name: '同比增长',
          type: 'line',
          stack: '总量',
          symbolSize: 6,
          lineStyle: {
            color: '#E99220',
          },
        },
      ] as Array<any>,
    };
    const refChartOption = ref(chartOption);
    const xTime = ref<string>('');
    const chartHeight = computed(() => `${props.height}px`);
    const setChartOption = data => {
      Difference.value = data.dqNum - data.num;
      const xAxis: string[] = [];
      const mapList: number[] = [];
      const tqMapList: number[] = [];
      if (data.mapList) {
        //日 截取到当前日期
        if (props.period == '日') {
          let time = moment().format('YYYY-MM-DD');
          let dataIndex = data.mapList.findIndex(item => item.dDate == time);
          if (dataIndex > 0) {
            data.mapList = data.mapList.slice(0, dataIndex + 1);
          }
        }
        data.mapList.forEach(item => {
          mapList.push(item.num);
          xAxis.push(item.dDate);
        });
      }
      if (data.tqMapList) {
        data.tqMapList.forEach(item => {
          tqMapList.push(item.num);
        });
      }
      refChartOption.value.xAxis.data = xAxis;
      refChartOption.value.series[0].data = mapList;
      //环比不显示虚线数据
      let timer = props.time;
      if (props.period == '月') {
        let text = props.time.split('-');
        timer = text[0] + '-' + text[1];
      }
      let resultIndex = xAxis.findIndex(item => item == timer);
      //环比取消虚线 添加对比数值
      if (props.ratio == 'H') {
        refChartOption.value.series[1].data = [];
        refChartOption.value.series[1].name = '';
        xTime.value = xAxis[resultIndex - 1];
        refChartOption.value.series[1].markPoint = null;
      } else if (props.ratio == 'N') {
        //既不是环比 同比取消虚线不添加对比值
        refChartOption.value.series[1].data = [];
        refChartOption.value.series[1].name = '';
        xTime.value = '';
        refChartOption.value.series[1].markPoint = null;
      } else if (props.ratio == 'T') {
        refChartOption.value.series[1].data = [];
        refChartOption.value.series[1].name = '';
        xTime.value = '';
        refChartOption.value.series[1].data = tqMapList;
        refChartOption.value.series[1].name = '前期警情趋势';
        refChartOption.value.series[1].markPoint = {
          symbolRotate: '-180',
          data: [
            {
              name: 'value',
              vlaue: '22',
              xAxis: timer,
              yAxis: tqMapList[resultIndex],
              itemStyle: {
                borderColor: 'red',
                normal: {
                  label: {
                    formatter: `${tqMapList[resultIndex]}`,
                    color: 'white', //气泡中字体颜色
                  },
                  color: 'grey',

                  borderWidth: 1, // 标注边线线宽，单位px，默认为1
                },
              },
              label: {
                formatter: `${tqMapList[resultIndex]}`,
                color: 'black', //气泡中字体颜色

                offset: [0, 14],
                textStyle: {
                  marginTop: '500px',
                },
              },
            },
          ],
        };
      }
      refChartOption.value.series[0].markPoint = {
        data: [
          {
            name: 'value',
            vlaue: '22',
            xAxis: timer,
            yAxis: mapList[resultIndex],
            itemStyle: {
              borderColor: 'red',
              normal: {
                label: {
                  formatter: `${mapList[resultIndex]}`,
                  color: 'white', //气泡中字体颜色
                },
                color:
                  props.yjLevel == '1'
                    ? '#FF283A'
                    : props.yjLevel == '2'
                    ? '#FF721C'
                    : props.yjLevel == '3'
                    ? '#ECD50D'
                    : '#1EDEFF',

                borderWidth: 1, // 标注边线线宽，单位px，默认为1
              },
            },
            label: {
              formatter: `${mapList[resultIndex]}`,
              color: 'black', //气泡中字体颜色
            },
          },
          {
            name: 'value2',
            vlaue: '22',
            xAxis: xTime.value,
            yAxis: mapList[resultIndex - 1],
            itemStyle: {
              borderColor: 'red',
              normal: {
                label: {
                  formatter: `${mapList[resultIndex]}`,
                  color: 'white ', //气泡中字体颜色
                },
                color: 'grey',
                borderWidth: 0, // 标注边线线宽，单位px，默认为1
              },
            },
            label: {
              formatter: `${mapList[resultIndex - 1]}`,
              color: 'black', //气泡中字体颜色
            },
          },
        ],
      };
    };

    const renderClickHandle = e => {
      const index = chartRef.value.getIndexByEvent(e);
      const item = props.data[index];
      emit('zrender:click', index, item);
    };
    const handleselected = e => {
      if (!e.selected.前期警情趋势) {
        chartOption.legend.data[1].icon = `image://${line4}`;
        setChartOption(props.data);
      } else {
        chartOption.legend.data[1].icon = line.value;
        setChartOption(props.data);
      }
    };
    //差值
    const Difference = ref<any>(0);
    watch(
      () => props.type,
      () => {
        if (props.type == '1') {
          areaStyle.value.normal = {
            // 填充色渐变
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#E99220' },
              // { offset: 0.5, color: 'rgba(58, 167, 255,0.4)' },
              { offset: 1, color: '#25272D' },
            ]),
          };
          color.value = '#E99220';
          chartOption.series[0].lineStyle.color = '#E99220';
          chartOption.series[0].itemStyle.normal.color = '#E99220';
          chartOption.series[1].itemStyle.normal.color = '#E99220';
          chartOption.series[1].itemStyle.normal.borderColor = '#E99220';
          chartOption.series[1].itemStyle.normal.lineStyle.color = '#E99220';
          chartOption.series[1].emphasis.itemStyle.color = '#E99220';
          chartOption.legend.data[1].icon = `image://${line1}`;
          line.value = `image://${line1}`;
        } else if (props.type == '2') {
          areaStyle.value.normal = {
            // 填充色渐变
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#1CCAFF' },
              // { offset: 0.5, color: 'rgba(58, 167, 255,0.4)' },
              { offset: 1, color: '#25272D' },
            ]),
          };
          color.value = '#1CCAFF';
          chartOption.series[0].lineStyle.color = '#1CCAFF';
          chartOption.series[0].itemStyle.normal.color = '#1CCAFF';
          chartOption.series[1].itemStyle.normal.color = '#1CCAFF';
          chartOption.series[1].itemStyle.normal.borderColor = '#1CCAFF';
          chartOption.series[1].itemStyle.normal.lineStyle.color = '#1CCAFF';
          chartOption.series[1].emphasis.itemStyle.color = '#1CCAFF';
          chartOption.legend.data[1].icon = `image://${line2}`;
          line.value = `image://${line2}`;
        } else {
          areaStyle.value.normal = {
            // 填充色渐变
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#3191FF ' },
              { offset: 1, color: '#25272D' },
            ]),
          };
          color.value = '#3191FF';
          chartOption.series[0].lineStyle.color = '#3191FF';
          chartOption.series[0].itemStyle.normal.color = '#3191FF';
          chartOption.series[1].itemStyle.normal.color = '#3191FF';
          chartOption.series[1].itemStyle.normal.borderColor = '#3191FF';
          chartOption.series[1].itemStyle.normal.lineStyle.color = '#3191FF';
          chartOption.series[1].emphasis.itemStyle.color = '#3191FF';
          chartOption.legend.data[1].icon = `image://${line3}`;
          line.value = `image://${line3}`;
        }
        setChartOption(props.data);
      },
      {
        immediate: true,
        deep: true,
      },
    );
    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.height,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.period,
      () => {
        setChartOption(props.data);
      },
    );
    onMounted(() => {
      setChartOption(props.data);
    });
    return {
      color,
      areaStyle,
      chartHeight,
      refChartOption,
      renderClickHandle,
      handleselected,
      chartRef,
      Difference,
      line,
      xTime,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style lang="less" scoped></style>
